const { CreateUser, getUserInfo, updateInfo, updateUserImport } = require('../services/UserService')
const { WillFriend, wildFriend } = require('../services/FriendService')

const jwt = require('jsonwebtoken')
const { JWT_SECURE } = require('../config/config_deafault')
//引入邮箱注册
const { sendMail, RandomNum } = require('../utils/mailer')
//redis
const { setRedis, getRedis } = require('../utils/redis')
const { token } = require('../config/config_deafault')
const { musicInfoExist } = require('../constant/musiclikeErrortype')
const axios = require('axios')
const FormData = require('form-data')

class UserController {
    //用户注册 
    async register(ctx, next) {
        const { user_password, user_nickname, user_email, image, imagekey } = ctx.request.body
        try {
            const res = await CreateUser(user_password, user_nickname, user_email, image, imagekey)

            ctx.body = {
                code: 0,
                message: "用户注册成功",
                result: {
                    nickname: res.dataValues.user_nickname
                }
            }
        } catch (error) {
            console.log(error);

        }
    }
    async login(ctx, next) {
        const { user_email } = ctx.request.body
        try {
            const { user_password, ...result } = await getUserInfo({ user_email })
            ctx.body = {
                code: '0',
                message: "用户登录成功",
                result: {
                    userinfo: {
                        name: result.user_nickname,
                        imgurl: result.image,
                        uid: result.user_id
                    },
                    token: jwt.sign(result, JWT_SECURE, { expiresIn: '1d' })
                }
            }
        } catch (error) {
            console.log(error);
        }

    }

    //发送验证码
    async sendEmail(ctx, next) {
        try {
            const { user_email } = ctx.request.body
            const isExist = await getRedis(user_email)
            if (isExist) {
                ctx.body = {
                    code: 200,
                    message: "验证码已发送,请稍后再试"
                };
                return
            }
            const code = RandomNum(4)
            const content = `<p>您的验证码是：<span style="color:lightskyblue">${code}</span><p>`
            setRedis(user_email, code)
            const result = await sendMail(user_email, content)
            ctx.body = {
                code: "200",
                message: '验证码发送成功',
                data: {
                    result: result,
                }
            }
        } catch (error) {
            console.log(error);

            ctx.body = {
                code: "404",
                result: "验证码发送失败"
            }
        }


    }

    // //更新用户信息
    // async updateInfo(ctx, next) {
    //     const { user_nickname } = ctx.request.body
    //     const { user_id } = ctx.state.user
    //     const result = await UpdateUseName({ user_id, user_nickname, image, imagekey })
    //     if (result !== null) {
    //         ctx.body = {
    //             code: 0,
    //             message: "用户修改昵称成功",
    //             result: {
    //                 user_nickname,
    //                 image
    //             }
    //         }
    //     }
    // }
    //更新用户密码
    //用户修改密码
    async changePassword(ctx, next) {
        const { user_password } = ctx.request.body
        const { id, user_nickname } = ctx.state.user
        // console.log(user_password);

        const res = await UpdateUsePwd(id, user_password)
        if (res) {
            ctx.body = {
                code: 0,
                message: "用户密码修改成功",
                result: {
                    user_name
                }
            }
        }
    }
    //删除照片

    async removePicture(ctx, next) {
        try {
            // 获取 query 参数
            const { Oldimagekey } = ctx.request.body;
            // 发送删除请求
            const res = await axios.delete(
                `http://skypro.afterglow26.cn:28080/api/v1/images/${Oldimagekey}`,
                {
                    headers: {
                        Authorization: token,
                        Accept: 'application/json',
                    },
                }
            );
            // 判断删除是否成功
            if (res.data.status === true) {
                ctx.body = {
                    code: '0',
                    message: '更新成功',
                    result: "",
                };
            }
            else {
                ctx.body = {
                    code: '404',
                    message: '删除失败',
                    result: "",
                };
            }
        } catch (error) {
            console.error('删除请求出错:', error.message);

            // 捕获错误并返回给客户端
            ctx.status = error.response ? error.response.status : 500;
            ctx.body = {
                code: '1',
                message: '删除请求失败',
                error: error.message,
            };
        }

        // await next();
    }

    //更新用户头像

    //文件处理
    async uploadFileTest(ctx, next) {
        try {
            const formData = new FormData()
            if (!ctx.request.files) return ctx.app.emit('error', musicInfoExist, ctx)
            ctx.request.files.forEach((files) => {
                formData.append('file', files.buffer, files.originalname)
            })
            const res = await axios.post(`http://skypro.afterglow26.cn:28080/api/v1/upload`, formData, {
                headers: {
                    Authorization: token,
                    "Content-Type": "multipart/form-data"
                }
            })
            if (res.data.status == true) {
                ctx.request.body.imagekey = res.data.data.key
                ctx.request.body.image = res.data.data.links.url
                await next()
            }
        } catch (error) {
            console.log(error);
        }

    }
    //更新头像
    async uploadImage(ctx, next) {
        const { user_id } = ctx.state.user
        const { image, imagekey } = ctx.request.body
        const res = await updateInfo(Object.assign({ user_id }, { image, imagekey }))
        await next()
    }
    //更新token
    async UpdateInfo(ctx, next) {
        const { user_id } = ctx.state.user
        try {
            const { user_password, ...result } = await getUserInfo({ user_id })
            ctx.body = {
                code: '0',
                message: "用户登录成功",
                result: {
                    userinfo: {
                        name: result.user_nickname,
                        imgurl: result.image,
                        uid: result.user_id
                    },
                    token: jwt.sign(result, JWT_SECURE, { expiresIn: '1d' })
                }
            }
        }
        catch (error) {
            console.log(error);
        }

    }
    //更新用户消息
    async updateUserImportInfo(ctx, next) {
        try {
            const { user_id } = ctx.state.user
            const { user_nickname = null, user_password = null } = ctx.request.body
            const res = await updateUserImport(Object.assign({ user_id }, { user_nickname, user_password }))
            if (res) {
                ctx.body = {
                    code: 0,
                    message: 'success',
                    result: '更新成功'
                }
            }
        } catch (error) {
            console.log(error);

        }

    }

    //查找用户
    async selectUser(ctx, next) {
        try {
            const { user_nickname } = ctx.request.query
            const { user_id: selectid } = ctx.state.user

            const res = await getUserInfo({ user_nickname })
            if (res) {
                const { user_id, user_nickname, image } = res
                let status = null
                const Friend = await wildFriend(selectid, user_id)
                const WillFriendlist = await WillFriend(selectid, user_id)
                if (Friend.length == 0 && WillFriendlist.length == 0) {
                    status = -1
                }
                else if (Friend.length > 0) {
                    console.log(Friend[0].status);
                    status = Friend[0].status
                }
                else if (WillFriendlist.length > 0) {
                    switch (WillFriendlist[0].status) {
                        case 0:
                            status = 1
                            break;
                        case 1:
                            status = 0;
                            break;
                        case 2:
                            status = 2
                            break;
                        case -1:
                            status = -1
                    }
                }

                const result = res?.user_id == selectid ? null : { user_id, user_nickname, image, status };

                ctx.body = {
                    code: 0,
                    message: 'success',
                    result: result
                }
                return
            }
            ctx.body = {
                code: 0,
                message: 'success',
                result: res
            }

        }
        catch (error) {
            console.log(error);

        }

    }

    async UserInfo(ctx, next) {
        const { id } = ctx.request.query
        const res = await getUserInfo({ user_id: id })
        const { user_id = '', user_nickname = '', image = '' } = res
        ctx.body = {
            code: 0,
            message: 'success',
            result: { user_id, user_nickname, image }
        }

    }
}


module.exports = new UserController()